package com.mk.legoscans2.helpers;


import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public class AccountAlertDialogHelper {
	
	public static AlertDialog getDialog(Context context, final AccountDialogOnSelectItemAction action)
	{
		final CharSequence[] accountNames = getAccountNames(context);
		
		AlertDialog.Builder accountDialogBuilder = new AlertDialog.Builder(context);
		accountDialogBuilder
			.setTitle("Choose an account")
			.setCancelable(false)
			.setItems(accountNames, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					CharSequence selectedAccount = accountNames[which];
					action.invoke(selectedAccount.toString(), true);
				}
			});
		
		return accountDialogBuilder.create();
	}
	
	public static CharSequence[] getAccountNames(Context context){
		
		AccountManager am = AccountManager.get(context);
		Account[] accounts = am.getAccountsByType("com.google");
		final CharSequence[] accountNames = new String[accounts.length + 1];
		accountNames[0] = "Local";
		for(int i = 0; i < accounts.length; i++) {
			accountNames[i+1] = accounts[i].name;
		}
		
		return accountNames;
	}
}
